﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.DAL;
using Medianamik.Core.Sugar;
using Medianamik.UI.Controls;
using Medianamik.UI.Web.MVP.View;
using Telerik.Web.UI;

namespace Medianamik.UI.Web.MVP.Presentation
{
    public abstract class ModulePresenterWithNodeTypeGrid<TView> : ModulePresenterWithGridBase<NodeType, TView>
        where TView : IModuleViewWithNodeTypeGrid
    {
        protected virtual Guid NodeType
        {
            get
            {
                var nodeType = BaseNodeType;
                if (View.QueryString[DefaultParamNames.ParentNodeTypeID] != null)
                {
                    View.QueryString[DefaultParamNames.ParentNodeTypeID].IsGuidInline(out nodeType);
                }
                return nodeType;
            }
        }

        protected override void BindBreadcrumbTrail()
        {
            base.BindBreadcrumbTrail();

            //if (nodeId != null)
            //{
            //    BreadcrumbBuilder.AppendNode(View.RawUrl, DefaultParamNames.NodeID, nodeId.Value, true);
            //}
            //else
            //{
            //    base.BindBreadcrumbTrail();
            //}
            //View.BreadcrumbTrail = BreadcrumbBuilder.ToString();
        }

        protected abstract Guid BaseNodeType { get; }

        protected override Guid? ParentNodeId
        {
            get { return NodeType; }
        }

        protected virtual bool IncludeBaseNodeType { get { return false; } }
        
        protected ModulePresenterWithNodeTypeGrid(TView view)
            : base(view)
        {
        }

        protected override void SetCustomGridColumnsAtCreation(GridItem item)
        {
            base.SetCustomGridColumnsAtCreation(item);

            SetDeleteButton((LinkButton)item.FindControl(View.DeleteButtonId), null);
        }

        protected override void SetCustomGridColumns(GridItem item, NodeType nodeType)
        {
            base.SetCustomGridColumns(item, nodeType);

            SetEditButton((HyperLink)item.FindControl(View.EditButtonId), nodeType);
            SetEditAttributesButton((HyperLink)item.FindControl(View.EditAttributesButtonId), nodeType);
            SetDeleteButton((LinkButton)item.FindControl(View.DeleteButtonId), nodeType);
        }

        protected virtual void SetEditButton(HyperLink editButton, NodeType nodeType)
        {
            if (editButton != null)
            {
                editButton.NavigateUrl = View.EditPageUrl.AddParam(DefaultParamNames.TypeID, nodeType.ID)
                                            .AddParam(DefaultParamNames.ReturnURL, EditReturnUrl.UrlEncodeBase64());
            }
        }

        protected virtual void SetEditAttributesButton(HyperLink attrButton, NodeType nodeType)
        {
            if (attrButton != null)
            {
                if (View.AttributesPageUrl != null)
                {
                    attrButton.NavigateUrl = View.AttributesPageUrl.AddParam(DefaultParamNames.TypeID, nodeType.ID);
                }
            }
        }

        protected virtual void SetDeleteButton(LinkButton deleteButton, NodeType nodeType)
        {
            if (deleteButton != null)
            {
                if (nodeType != null && (nodeType.IsAdmin || NodeTypeManager.GetAllChildTypes(nodeType.ID).Count > 0))
                {
                    deleteButton.Enabled = false;
                    deleteButton.Text = "<img alt=\"\" src=\"/medianamik/images/Icones/Ico_SupprimerInactif.gif\" />";
                    deleteButton.OnClientClick = "";
                }
                else
                {
                    deleteButton.Command += OnNodeTypeDelete;
                }
            }
        }

        protected virtual void OnNodeTypeDelete(object sender, CommandEventArgs e)
        {
            if(e.CommandName == "delete" && e.CommandArgument != null)
            {
                Guid typeId;
                if(e.CommandArgument.ToString().IsGuidInline(out typeId))
                {
                    NodeTypeManager.DeleteNodeType(typeId);
                    Bind();
                }
            }
        }

        protected override void SetNameColumn(ITextControl nameGridItem, NodeType nodeTypeProp)
        {
            nameGridItem.Text = ChildrenListingPageUrl != null
                ? string.Format("<a href=\"{0}\">{1}</a>", ChildrenListingPageUrl.AddParam(ChildrenListingPageParamName, nodeTypeProp.ID), nodeTypeProp.GetLocalizedName(MedianamikContext.Current.CurrentUICulture))
                : nodeTypeProp.GetLocalizedName(MedianamikContext.Current.CurrentUICulture);
        }

        protected virtual List<NodeType> GetNodeTypes()
        {
            var baseType = NodeTypeManager.GetNodeType(NodeType);
            var typeCollection = NodeTypeManager.GetAllChildTypes(NodeType)
                .Where(t => t.Depth == baseType.Depth + 1)
                .ToList();

            if (baseType != null && IncludeBaseNodeType)
                typeCollection.Add(baseType);

            return typeCollection;
        }

        protected virtual List<NodeType> GetNodeTypesForBreadcrumbs()
        {
            return NodeTypeManager.GetParentTypes(NodeType, true)
                .Where(p => p.Path.Contains(BaseNodeType.ToString()))
                .ToList();
        }

        protected override PagedCollection<NodeType> GetData()
        {
            var typeCollection = GetNodeTypes();

            return new PagedCollection<NodeType>(
                    typeCollection.OrderBy(x => x.GetLocalizedName(CurrentEditionCulture))
                        .Skip((PageIndex - 1)*PageSize)
                        .Take(PageSize),
                    typeCollection.Count);
        }
    }
}